package ch.fhnw.qualiscan.core.helpers;

import java.io.Serializable;

import ch.fhnw.qualiscan.ApplicationData;
import ch.fhnw.qualiscan.Config;
import ch.fhnw.qualiscan.application.controllers.PageNotFound;
import ch.fhnw.qualiscan.core.Controller;
import eu.livotov.tpt.TPTApplication;

@SuppressWarnings("serial")
public class ControllerLoader implements Serializable {
	
	ApplicationData appData = (ApplicationData) TPTApplication.getCurrentApplication().getMainWindow().getData();
	
	private UserSessionHelper userSessionHelper = new UserSessionHelper();
	
	public void loadController(String controllerString) {
		
		try {
    		Class<?> newController = null;
    		
    		try {
    			newController = Class.forName("ch.fhnw.qualiscan.application.controllers."+controllerString+"");
    		} catch(Exception ClassNotFoundException) {
    			newController = null;
    		}
    		
            if(newController != null) {

            	Controller controller = (Controller) newController.newInstance();
            	controller.setNeededPermissions();
            	
            	if (!checkPermissions(controller)) {
            		appData.getLoaderLib().setUrlFragment(0, "PermissionDenied");
            		return;
            	}
            	else {
            		controller.loadUserSession();
            		controller.initHibernateSession();
            		controller.loadModels();
            		controller.init();
            		controller.setView();
            		controller.loadView();
            		
            		appData.setCurrentController(controller);
            	}
            	
        		
            } else {
            	appData.getLoaderLib().setUrlFragment(0, "PageNotFound");
            }
            
        } catch (Exception ex) {
        	ex.printStackTrace();
        }
		
	}
	
	private boolean checkPermissions(Controller controller) {
		boolean permissionGranted = true;
		
		for (int i = 0; i < controller.neededPermissions.size(); i++) {
			if (controller.neededPermissions.get(i) == Permissions.LOGGEDIN) {
				if (!userSessionHelper.isUserSessionSet()) {
					permissionGranted = false;
				}
			}
			
			if (controller.neededPermissions.get(i) == Permissions.ADMINISTRATOR) {
				if (userSessionHelper.getUser().getRole().getId() != Config.ADMINISTRATOR_ID) {
					permissionGranted = false;
				}
			}
			
			if (controller.neededPermissions.get(i) == Permissions.COORDINATOR) {
				if (userSessionHelper.getUser().getRole().getId() != Config.COORDINATOR_ID) {
					permissionGranted = false;
				}
			}
		}
		
		controller.neededPermissions.clear();
		
		return permissionGranted;
	}

}
